package edu.neelsys.mvc;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import edu.neelsys.business.search.SearchService;
import edu.neelsys.mvc.util.Constants;
import edu.neelsys.mvc.util.ErrorMessage;
import edu.neelsys.objectmodel.dbentites.CollegeSearchView;
import edu.neelsys.objectmodel.queryviews.CollegeSearchDTO;
import edu.neelsys.objectmodel.userauth.LoggedUser;

@Controller
@RequestMapping("/collegeSearch.html")
public class SearchController  {

	private SearchService searchService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax
	 * .servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
	 * java.lang.Object, org.springframework.validation.BindException) onSubmit
	 * method gets the request and validate user credential using user name and
	 * password. On validation error it shows error message.
	 */
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {

		LoggedUser loggedUser = (LoggedUser) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();

		List<CollegeSearchView> searchList = searchService
				.getSearchData(loggedUser.getUsername());

		String errorMessage = ErrorMessage.message;
		ErrorMessage.message = null;
		if (errorMessage != null) {

			ModelAndView mav = new ModelAndView(Constants.SEARCH_SUCCESS_VIEW,
					Constants.SEARCH_FORM_MODEL, searchList);
			mav.addObject(errors);
			return mav;
		} else {

			
			System.out.println("The SearchList in Searchcontroller is===>..+"
					+ searchList.size());

			ModelAndView successmav = new ModelAndView(Constants.SEARCH_SUCCESS_VIEW,
					Constants.SEARCH_FORM_MODEL, searchList);
			successmav.addObject(searchList);
			return successmav;

		}

	}
}
